package com.czxy.Servlet;

import cn.itcast.servlet.BaseServlet;
import com.czxy.Service.DownLoadService;
import com.czxy.domain.DownLoad;


import javax.jnlp.DownloadService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

@WebServlet("/DownLoadS")
public class DownLoadServlet extends BaseServlet {
   private DownLoadService downLoadService = new DownLoadService();
   @Override
   public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
   {
      this.doPost(request, response);
   }

   public void doPost(HttpServletRequest request, HttpServletResponse response,String videoAddress,String filename) throws ServletException, IOException {
      //当文件名不是英文名的时候，最好使用url解码器去编码一下，
      filename=URLEncoder.encode(filename,"UTF-8");
      //将响应的类型设置为图片
      response.setContentType("image/jpeg");
      response.setHeader("Content-Disposition", "attachment;filename=" + filename);
      //好了 ，现在通过IO流来传送数据
      InputStream input=new FileInputStream(new File(videoAddress));
      //设置文件大小
      response.setHeader("Content-Length", ""+new File(videoAddress).length());
      OutputStream output = response.getOutputStream();
      byte[]buff=new byte[1024*10];//可以自己 指定缓冲区的大小
      int len=0;
      while((len=input.read(buff))>-1)
      {
         output.write(buff,0,len);
      }
      //关闭输入输出流
      input.close();
      output.close();
   }

   //获取数据库中存储的视频信息
   public void selectAllVideo() throws ServletException, IOException {
       List<DownLoad> allVideo = downLoadService.findAllVideo();
       //把视频信息反馈给浏览器页面
       getRequest().setAttribute("VideoList",allVideo);
       getRequest().getRequestDispatcher("/pages/stu-video.jsp").forward(getRequest(),getResponse());
   }



   public void DownLoad() throws ServletException, IOException {
       //获取浏览器传递的参数  视频路径
       String videoId = getRequest().getParameter("videoId");
       String videoName = getRequest().getParameter("videoName");
       //在数据库中查询文件的真实路径
       String videoAddress = downLoadService.findVideoAddress(videoId);

       doPost(getRequest(),getResponse(),videoAddress,videoName);
   }
}
